const { request } = require('../../../utils/request');

Page({
  data: {
    products: [],
    page: 1,
    pageSize: 10,
    loadingMore: false,
    noMoreData: false
  },

  onShow() {
    this.resetData();
    this.loadProducts();
  },

  // 重置数据
  resetData() {
    this.setData({
      products: [],
      page: 1,
      loadingMore: false,
      noMoreData: false
    });
  },

  // 加载产品列表
  async loadProducts() {
    if (this.data.noMoreData) return;

    try {
      const { page, pageSize } = this.data;
      this.setData({ loadingMore: true });

      const res = await request({
        url: '/product',
        method: 'GET',
        data: {
          show_all: true,
          page,
          page_size: pageSize
        },
        showLoading: false
      });

      if (res.code === 2000) {
        const newProducts = res.data.items || [];
        const total = res.data.total || 0; // 假设接口返回总数据量
        const currentTotal = this.data.products.length + newProducts.length;

        this.setData({
          products: [...this.data.products, ...newProducts],
          page: page + 1,
          noMoreData: currentTotal >= total || newProducts.length < pageSize
        });
      }
    } catch (error) {
      wx.showToast({ title: '获取产品列表失败', icon: 'none' });
    } finally {
      this.setData({ loadingMore: false });
    }
  },

  // 加载更多产品
  async loadMoreProducts() {
    if (this.data.loadingMore || this.data.noMoreData) return;
    await this.loadProducts();
  },

  // 跳转到添加产品页面
  navigateToAddPage() {
    wx.navigateTo({
      url: '/page/component/productAdd/index'
    });
  },

  // 修改产品
  async editProduct(e) {
    const productId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/page/component/productEdit/index?id=${productId}`
    });
  },

  // 删除产品
  async deleteProduct(e) {
    const productId = e.currentTarget.dataset.id;
    wx.showModal({
      title: '提示',
      content: '确定要删除该产品吗？',
      success: async (res) => {
        if (res.confirm) {
          try {
            const res = await request({
              url: `/product/${productId}`,
              method: 'DELETE'
            });
            if (res.code === 2000) {
              wx.showToast({ title: '删除成功' });
              this.resetData();
              this.loadProducts();
            } else {
              wx.showToast({ title: res.message || '删除失败', icon: 'none' });
            }
          } catch (error) {
            wx.showToast({ title: '请求失败，请稍后重试', icon: 'none' });
          }
        }
      }
    });
  },

  // 切换产品上下架状态
  async toggleProductStatus(e) {
    const productId = e.currentTarget.dataset.id;
    const currentUsable = e.currentTarget.dataset.usable;
    const newUsable = !currentUsable;

    try {
      wx.showLoading({ title: newUsable ? '上架中...' : '下架中...' });
      const res = await request({
        url: `/product/${productId}/shelf`,
        method: 'PUT',
        data: {
          usable: newUsable
        }
      });
      wx.hideLoading();

      if (res.code === 2000) {
        // 更新本地数据
        const products = this.data.products.map(product => {
          if (product.id === productId) {
            return { ...product, usable: newUsable };
          }
          return product;
        });
        this.setData({ products });

        wx.showToast({ 
          title: newUsable ? '上架成功' : '下架成功',
          icon: 'success'
        });
      } else {
        wx.showToast({ 
          title: res.message || (newUsable ? '上架失败' : '下架失败'),
          icon: 'none'
        });
      }
    } catch (error) {
      wx.hideLoading();
      wx.showToast({ 
        title: '请求失败，请稍后重试',
        icon: 'none'
      });
      console.error('切换产品状态请求出错:', error);
    }
  }
});